<?php

namespace App\Console\Commands\Movie;

use Illuminate\Console\Command;
use App\Models\Movie;
use App\Bots\CommentBots;
use App\Bots\CreateUserBots;

class GetComments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'movie:get-comments
                            {--id=0 : 采集指定 ID 的电影详情（id 来自豆瓣）}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取短评';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while( $movie = Movie::where('is_crawler_comments', false)->doesntHave('comments')->where('douban_id', '>', 0)->first()) {
            $this->info('正在获取电影 ' . $movie->short_name . ' 的短评');
            $comments = new CommentBots($movie);
            $c = $comments->run();
            $info = collect($c);
            $info->map(function($item) use ($movie) {
                $createUser = new CreateUserBots($item['author']);
                $user = $createUser->create();
                $movie->comments()->create([
                    'user_id' => $user->id,
                    'content' => $item['content'],
                    'source' => 'douban',
                    'created_at' => $item['created_at'],
                ]);
            });
            $movie->update(['is_crawler_comments' => true]);
        }
        $this->info('处理完成');
    }
}
